package cn.kill.orderservice.service.order.impl;

import cn.kill.orderservice.mapper.order.OrderMapper;
import cn.kill.orderservice.pojo.PayOrder;
import cn.kill.orderservice.service.order.OrderService;
import cn.kill.orderservice.service.base.BaseService;
import cn.kill.orderservice.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;


/**
 * @author 张在成
 */
@Service
public class OrderServiceImpl extends BaseService<PayOrder> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;


    @Override
    public PayOrder saveOrder(String body, double money) {
        PayOrder payOrder=null;
        try {
            payOrder=new PayOrder();
            payOrder.setOrderNo(System.currentTimeMillis()+"");
            payOrder.setBody(body);
            payOrder.setMoney(money);
            payOrder.setStatus(0);
            payOrder.setPayTime(DateUtils.getCurrentTime(new Date()));
            Integer i = super.insert(payOrder);
            if (i==null||i.equals("")){
                throw  new Exception("订单保存失败");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return payOrder;
    }

    @Override
    public PayOrder selectOrderDetail(String orderNo) {

        PayOrder payOrder=null;
        try {
            PayOrder order=new PayOrder();
            order.setOrderNo(orderNo);
            payOrder = super.selectOne(order);
        }catch (Exception e){
            e.printStackTrace();
            return  null;
        }
        return payOrder;
    }

    @Override
    public boolean paySucess(String orderNo, String payNo, Date payTime) {
        //修改订单状态之前，先查询订单是否存在
        try {
            PayOrder payOrder = selectOrderDetail(orderNo);
            if (payOrder==null){
                throw  new Exception("该笔订单不存在");
            }
            //查询订单状态是否存在
            if (payOrder.getStatus()==1){
                return true;
            }
            //修改订单状态和支付时间
            PayOrder order=new PayOrder();
            order.setId(payOrder.getId());
            order.setStatus(1);
            order.setPayNo(payNo);
            order.setBody(payOrder.getBody());
            order.setMoney(payOrder.getMoney());
            order.setPayTime(DateUtils.getCurrentTime(payTime));
            Example example=new Example(PayOrder.class);
            Example.Criteria criteria =example.createCriteria();
            criteria.andEqualTo("orderNo",orderNo);
            order.setOrderNo(orderNo);
            super.updateByPrimaryKey(order);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }


}
